<%@ page pageEncoding="UTF-8"%>
<%@ include file="/common/token.jsp"%>
<%
	String id = input.getDesc("template_id", "-1");
	Integer uid = token.getUid();
	List<Map> templates = QBuilder.db("basedb").select("new map(id as template_id, template_name as title, template_type as detail)").from("visit_template").where(new Where("id =", id).and("status = ", STATUS_ENABLE)).query().getResultObj();
    if (isEmpty(templates)) {
        msg = new Message(30041, "暂无随访模板");
		Tools.encryptPrint(out, msg);
        return;
    }
	Map template = templates.get(0);
	String templateId = Tools.getDesc(template.get("template_id"), "-1");
	// 查询节点
	List<Map> points = QBuilder.db("basedb").select("new map(id as point_id, title as title,time_difference as time_difference)").from("visit_point").where(new Where("template_id =", templateId).and("status = ", STATUS_ENABLE)).order("show_order", QBuilder.asc).query().getResultObj();
	if (!isEmpty(points)) {
		template.put("start_point", points.get(0));
		template.put("end_point", points.get(points.size() - 1));
		template.put("point_count", points.size());
		template.put("visit_period", points.get(points.size() - 1).get("time_difference"));
		// 查询量表
		String pointIds = "-1";
		for (int i = 0; i < points.size(); i++) {
			Map point = points.get(i);
			pointIds += "," + Tools.getDesc(point.get("point_id"), "-1");
		}
		List<Map> surveys = QBuilder.db("basedb").select("new map(s.id as survey_id, s.title as title)").from("visit_point_link vpl, Survey s").where(new Where("vpl.link_type = 0").and("vpl.status = ", STATUS_ENABLE).and("vpl.point_id in ("+pointIds+")").and("vpl.link_id=s.id")).group("vpl.link_id").query().getResultObj();
		template.put("surveys", surveys);
	}
	// 查询是否已经存在
	List<Long> count = QBuilder.db("basedb").select("count(oid)").from("visit_template").where(new Where("oid =" + id + " or id=" + id).and("status = ", STATUS_ENABLE).and("uid=", uid)).query().getResultObj();
	Long num = count.get(0);
	template.put("added", num > 0 ? 1:0);
	msg.put("data", template);
	Tools.encryptPrint(out, msg); 	
%>